package world.xuewei.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import world.xuewei.dao.MedicineDao;
import world.xuewei.entity.Medicine;
import world.xuewei.entity.MedicineDoc;

import java.io.IOException;
import java.util.List;

import static world.xuewei.constant.MedicalMapping.MAPPING_TEMPLATE;

@Service
public class EsService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private MedicineDao medicineDao;
    // 创建索引
    public void createAiIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("medicine");
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }
    // 删除索引库
    public void deleteAiIndex() throws IOException {
        client.indices().delete(new DeleteIndexRequest("medicine"), RequestOptions.DEFAULT);
    }
    //批量新增doc
    void BulkRequest() throws IOException {
        //批量查询数据
        List<Medicine> medicines = medicineDao.list();
        //1.创建Request对象
        BulkRequest bulkRequest = new BulkRequest();
        //2.遍历hotel集合，将hotel转化成文档对象，添加到bulkRequest中
        for (Medicine medicine : medicines) {
            //转换成文档类型HotelDoc
            MedicineDoc medicineDoc = new MedicineDoc(medicine);
            //创建新增文档的Request对象
            bulkRequest.add(new IndexRequest("medicine")
                    .id(medicineDoc.getId().toString())
                    .source(JSON.toJSONString(medicineDoc), XContentType.JSON));
        }
        //3.发起请求
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }


    // 添加数据
    void AddMediniceByname(String name) throws IOException {
        //根据名字查询
        QueryWrapper<Medicine> queryWrapper = new QueryWrapper<Medicine>();
        queryWrapper.eq("medicine_name", name);
        Medicine medicine = medicineDao.selectOne(queryWrapper);
        //转化成文档类型
        MedicineDoc medicineDoc = new MedicineDoc(medicine);
        //1.准备Request请求对象
        IndexRequest request = new IndexRequest("medicine").id(medicineDoc.getId().toString());
        //2.JSON文档
        request.source(JSON.toJSONString(medicineDoc), XContentType.JSON);
        //3.发起请求
        client.index(request, RequestOptions.DEFAULT);
    }

    // 修改数据
    void updateMedicineById(String id) throws IOException {
        // 根据id查询现有文档
        QueryWrapper<Medicine> queryWrapper = new QueryWrapper<Medicine>();
        queryWrapper.eq("id", id);
        Medicine medicine = medicineDao.selectOne(queryWrapper);

        if (medicine != null) {
            // 将查询到的对象转换成文档类型
            MedicineDoc medicineDoc = new MedicineDoc(medicine);

            // 准备UpdateRequest请求对象
            UpdateRequest request = new UpdateRequest("medicine", id)
                    .doc(JSON.toJSONString(medicineDoc), XContentType.JSON);

            try {
                UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
                if (response.getResult() == DocWriteResponse.Result.UPDATED) {
                    System.out.println("文档更新成功");
                } else if (response.getResult() == DocWriteResponse.Result.NOOP) {
                    System.out.println("文档没有变化，未执行更新");
                } else if (response.getResult() == DocWriteResponse.Result.NOT_FOUND) {
                    System.out.println("文档不存在");
                }
            } catch (ElasticsearchException e) {
                if (e.status() == RestStatus.CONFLICT) {
                    // 版本冲突处理逻辑
                }
                System.out.println("更新操作异常：" + e.getMessage());
            }
        } else {
            System.out.println("找不到对应id的文档");
        }
    }

    // 删除数据
    void DeleteMedicineById(String id) throws IOException {

        //1.准备Request请求对象
        DeleteRequest request = new DeleteRequest("medicine", id);
        //2.发起请求
        client.delete(request, RequestOptions.DEFAULT);
    }
}
